#include <stdlib.h>
#include "buzzer_porting.h"
#include "..\ti_msp_dl_config.h"

#define BUZZER_TASK_PERIOD 30

#define BUZZER_PIN          BUZZER_PIN_0_PIN

/* 全系统全局变量 */
BuzzerObjectTypeDef buzzer;
static BuzzerCtrlTypeDef buzzer1_ctrl_ququeHandle; /* 蜂鸣器控制队列Handle */

static void buzzer_set(BuzzerObjectTypeDef *self, uint8_t state);         /* pwm设置接口 */
static int put_ctrl_block(BuzzerObjectTypeDef *self, BuzzerCtrlTypeDef *p);   /* 控制入队接口 */
static int get_ctrl_block(BuzzerObjectTypeDef *self, BuzzerCtrlTypeDef *p);   /* 控制出队接口 */


/**
  * @brief 蜂鸣器相关的初始化
  * @retval None.
  *
*/
void buzzer_init(void)
{
	buzzer_object_init(&buzzer);
	buzzer.id = 1;
    buzzer.set = buzzer_set;
	buzzer.get_ctrl_block = get_ctrl_block;
	buzzer.put_ctrl_block = put_ctrl_block;
}


/**
  * @brief 系统定时器回调
  * @detials 定时刷新LED灯状态，定时时间通过 CubeMx 设置
  * @retval None.
  *
*/
void buzzer_timer_callback(void *argument)
{
    buzzer_task_handler(&buzzer, BUZZER_TASK_PERIOD);
}


/**
  * @brief 蜂鸣器 PWM 设置接口
  * @param freq PWM 频率
  * @retval None.
  *
*/
static void buzzer_set(BuzzerObjectTypeDef *self, uint8_t state)
{
	if (state == 0)
    {
        DL_GPIO_clearPins(BUZZER_PORT, BUZZER_PIN);
    }
    else
    {
        DL_GPIO_setPins(BUZZER_PORT, BUZZER_PIN);
    }
}

static int8_t simulateQueuePut(BuzzerCtrlTypeDef *self, BuzzerCtrlTypeDef *p)
{
    self->data_effective = 1;
    self->repeat = p->repeat;
    self->ticks_on = p->ticks_on;
    self->ticks_off = p->ticks_off;
    return 0;
}

static int8_t simulateQueueGet(BuzzerCtrlTypeDef *self, BuzzerCtrlTypeDef *p)
{
    if (self->data_effective == 0)
    {
        return -1;
    }
    self->data_effective = 0;
    p->repeat = self->repeat;
    p->ticks_on = self->ticks_on;
    p->ticks_off = self->ticks_off;
    return 0;
}
/**
  * @brief 蜂鸣器控制队列入队接口
  * @param p 要出队的控制参数结构体指针
  * @retval 0 成功
  * @retval !=0 失败 
  *
*/
static int put_ctrl_block(BuzzerObjectTypeDef *self, BuzzerCtrlTypeDef *p) {
	return (int)simulateQueuePut(&buzzer1_ctrl_ququeHandle, p);
}

/**
  * @brief 蜂鸣器控制队列出队接口
  * @param  出队数据的存储指针
  * @retval 0 成功
  * @retval !=0 失败 
  *
*/
static int get_ctrl_block(BuzzerObjectTypeDef *self, BuzzerCtrlTypeDef *p) {
	return (int)simulateQueueGet(&buzzer1_ctrl_ququeHandle, p);
}


